using System;
using System.Collections.Generic;
using System.Text;

namespace ExtendBLL
{
    public class Vote : LabMS.BLL.Vote
    {
        public void Insert(LabMS.Model.VoteJson voteJson)
        {
            LabMS.Model.Vote voteInfo = new LabMS.Model.Vote();

            voteInfo.VoteTitle = voteJson.Title;
            voteInfo.VoteStartTime = DateTime.Now;

            voteInfo.VoteLimit = voteJson.Limit;

            voteInfo.key = base.Add(voteInfo); // Insert vote

            foreach (LabMS.Model.VoteItemJson item in voteJson.Items)
            {
                LabMS.Model.VoteItem voteItemInfo = new LabMS.Model.VoteItem();
                LabMS.BLL.VoteItem voteItem = new LabMS.BLL.VoteItem();
                voteItemInfo.VoteID = voteInfo.key;
                voteItemInfo.VoteItemContent = item.Title;

                voteItemInfo.key = voteItem.Add(voteItemInfo); // Insert Item

                foreach (LabMS.Model.VoteAnswerJson answer in item.Answers)
                {
                    LabMS.Model.VoteAnswer voteAnswerInfo = new LabMS.Model.VoteAnswer();
                    LabMS.BLL.VoteAnswer voteAnswer = new LabMS.BLL.VoteAnswer();

                    voteAnswerInfo.VoteItemID = voteItemInfo.key;
                    voteAnswerInfo.VoteAnswerContent = answer.Name;

                    voteAnswer.Add(voteAnswerInfo); // Insert answer
                }
            }
        }

        public void DeleteFullInfo(int voteID)
        {
            StringBuilder sb = new StringBuilder();

            sb.Append("delete from VoteAnswer where VoteItemID in ");
            sb.Append("( select vi.[key] from VoteItem vi where vi.VoteID = @VoteID ); ");
            sb.Append("delete from VoteItem where VoteID = @VoteID;");
            sb.Append("delete from VoteRecordDetail where VoteRecordID in ");
            sb.Append("( select [ID] from VoteRecord where VoteID = @VoteID ); ");
            sb.Append("delete from VoteRecord Where VoteID = @VoteID;");
            sb.Append("delete from Vote Where Vote.[key] = @VoteID;");

            Maticsoft.DBUtility.DbHelperSQL.ExecuteSql(
                sb.ToString(),
                new System.Data.SqlClient.SqlParameter(
                    "@VoteID",
                    voteID
                )
            );
        }

        public LabMS.Model.VoteJson GetJsonModel(int voteID)
        {
            LabMS.Model.VoteJson json = new LabMS.Model.VoteJson();

            LabMS.Model.Vote voteInfo = base.GetModel(voteID);

            if (voteInfo == null)
            {
                return json;
            }

            VoteItem voteItem = new VoteItem();

            json.Title = voteInfo.VoteTitle;
            json.Limit = voteInfo.VoteLimit.Value;
            json.ID = voteID;
            json.Items = voteItem.GetJsonVoteItems(voteID);

            return json;
        }
    }
}
